﻿﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;

public partial class index : System.Web.UI.Page
{
    bool m_byEmail = false;
    string m_GLOBAL_LOCATION;
    string m_GLOBAL_INFO;


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string photoLink = Request.QueryString["photo"];
            string bound = @"false";

            if (photoLink != null)
            {
                directFromDB(photoLink);
                bound = @"true";
                if (!ClientScript.IsStartupScriptRegistered("Google Maps"))
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "Google Maps", string.Format("init_map_open('map_canvas',{0}, {1}," + bound.ToString() + ")", m_GLOBAL_LOCATION, m_GLOBAL_INFO), true);
            }
            else
            {
                populateFromDB();

                if (!ClientScript.IsStartupScriptRegistered("Google Maps"))
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "Google Maps", string.Format("init_map('map_canvas',{0}, {1}," + bound.ToString() + ")", m_GLOBAL_LOCATION, m_GLOBAL_INFO), true);

            }
        }
    }

    protected void directFromDB(string photoLink)
    {
        var markers = new List<string>();
        var infoWindowContents = new List<string>();
        photoLink = @"images/UploadImage/" + photoLink;

        WBDataClassesDataContext db = new WBDataClassesDataContext();

        var gans = from g in db.BB_UPLOAD_DATAs
                   from gg in db.WEB_USERs
                   where g.ImageName == photoLink && g.UserID == gg.ID
                   select new
                   {
                       g.ImageName,
                       g.Latitude,
                       g.Longitude,
                       g.UserText,
                       gg.Email
                   };

        foreach (var gan in gans)
        {
            markers.Add(string.Format(@"{{position: new google.maps.LatLng({0},{1})}}", gan.Latitude, gan.Longitude));

            string info = string.Format(@"{{content: 
""<div class=\""mapInfoBox\"" id=\""content\""><img src=\""{0}\"" alt=\""User Photo\"" width=\""341\"" height=\""258\"" hspace=\""8\"" vspace=\""0\"" class=\""userMapPhoto\"" /><div class=\""mapInfo\""><strong>Location</strong><br/><strong>Lat:</strong> {1} <strong>Long:</strong> {2}<br/><br/><strong>Description:</strong><br/>{3}<br/><br/></div><div class=\""mapEmailInfo\""><strong>Email:</strong><br/><a href=\""mailto:{4}\"">{4}</a></div></div>""}}", gan.ImageName, gan.Latitude, gan.Longitude, gan.UserText.TrimEnd(), gan.Email);

            infoWindowContents.Add(info);
        }

        m_GLOBAL_LOCATION = "[" + string.Join(",", markers.ToArray()) + "]";
        m_GLOBAL_INFO = "[" + string.Join(",", infoWindowContents.ToArray()) + "]";
    }

    protected void populateFromDB()
    {
        var markers = new List<string>();
        var infoWindowContents = new List<string>();

        WBDataClassesDataContext db = new WBDataClassesDataContext();

        var gans = from g in db.BB_UPLOAD_DATAs
                   from gg in db.WEB_USERs
                   where g.UserID == gg.ID
                   select new
                   {
                       g.ImageName,
                       g.Latitude,
                       g.Longitude,
                       g.UserText,
                       gg.Email
                   };



        foreach (var gan in gans)
        {
            markers.Add(string.Format(@"{{position: new google.maps.LatLng({0},{1})}}", gan.Latitude, gan.Longitude));

            string info = string.Format(@"{{content: 
""<div class=\""mapInfoBox\"" id=\""content\""><img src=\""{0}\"" alt=\""User Photo\"" width=\""341\"" height=\""258\"" hspace=\""8\"" vspace=\""0\"" class=\""userMapPhoto\"" /><div class=\""mapInfo\""><strong>Location</strong><br/><strong>Lat:</strong> {1} <strong>Long:</strong> {2}<br/><br/><strong>Description:</strong><br/>{3}<br/><br/></div><div class=\""mapEmailInfo\""><strong>Email:</strong><br/><a href=\""mailto:{4}\"">{4}</a></div></div>""}}", gan.ImageName, gan.Latitude, gan.Longitude, gan.UserText.TrimEnd(), gan.Email);

            infoWindowContents.Add(info);
        }

        m_GLOBAL_LOCATION = "[" + string.Join(",", markers.ToArray()) + "]";
        m_GLOBAL_INFO = "[" + string.Join(",", infoWindowContents.ToArray()) + "]";
    }

    protected void populateFromDBByEmail(string emailAddress)
    {
        var markers = new List<string>();
        var infoWindowContents = new List<string>();

        WBDataClassesDataContext db = new WBDataClassesDataContext();

        var gans = from g in db.BB_UPLOAD_DATAs
                   from gg in db.WEB_USERs
                   where g.UserID == gg.ID && gg.Email == emailAddress
                   select new
                   {
                       g.ImageName,
                       g.Latitude,
                       g.Longitude,
                       g.UserText,
                       gg.Email
                   };



        foreach (var gan in gans)
        {
            markers.Add(string.Format(@"{{position: new google.maps.LatLng({0},{1})}}", gan.Latitude, gan.Longitude));

            string info = string.Format(@"{{content: 
""<div class=\""mapInfoBox\"" id=\""content\""><img src=\""{0}\"" alt=\""User Photo\"" width=\""341\"" height=\""258\"" hspace=\""8\"" vspace=\""0\"" class=\""userMapPhoto\"" /><div class=\""mapInfo\""><strong>Location</strong><br/><strong>Lat:</strong> {1} <strong>Long:</strong> {2}<br/><br/><strong>Description:</strong><br/>{3}<br/><br/></div><div class=\""mapEmailInfo\""><strong>Email:</strong><br/><a href=\""mailto:{4}\"">{4}</a></div></div>""}}", gan.ImageName, gan.Latitude, gan.Longitude, gan.UserText.TrimEnd(), gan.Email);

            infoWindowContents.Add(info);
        }

        m_GLOBAL_LOCATION = "[" + string.Join(",", markers.ToArray()) + "]";
        m_GLOBAL_INFO = "[" + string.Join(",", infoWindowContents.ToArray()) + "]";
    }

    protected void Bt_Login_Click(object sender, EventArgs e)
    {
        string HTML_userName = String.Format("{0}", Request.Form[@"userName"]);
        string HTML_passWord = String.Format("{0}", Request.Form[@"passWord"]);


        WBDataClassesDataContext db = new WBDataClassesDataContext();

        var users = from u in db.WEB_USERs
                    where u.UserTypeID == 1
                    select new
                    {
                        u.FirstName,
                        u.Email,
                        u.Password
                    };
        bool Success = false;

        foreach (var user in users)
        {
            if (user.Email == HTML_userName && user.Password == HTML_passWord)
            {
                Success = true;
                Session["Logged"] = "Yes";
                Session["User"] = user.FirstName;
                break;
            }
        }

        if (Success)
            Response.Redirect("Admin.aspx");
        else
        {
            ScriptManager.RegisterClientScriptBlock(DownloadPanel, typeof(UpdatePanel), "jscript", @"alert(""There is problem with the Username/Password , Please Try again"")", true);
        }
    }
    protected void Bt_ByEmail_Click(object sender, EventArgs e)
    {
        string HTML_email = String.Format("{0}", Request.Form[@"searchEmail"]);
        if (HTML_email != "")
            populateFromDBByEmail(HTML_email);
        else
            populateFromDB();

        string script = string.Format("init_map('map_canvas',{0}, {1}, true)", m_GLOBAL_LOCATION, m_GLOBAL_INFO);
        ScriptManager.RegisterClientScriptBlock(pnlHelloWorld, typeof(UpdatePanel), "jscript", script, true);
    }

    protected void Bt_DownloadLink_Click(object sender, EventArgs e)
    {
        string script;
        string downloadEmail = String.Format("{0}", Request.Form[@"Txt_Downloademail"]).ToLower();
        if (downloadEmail == "")
            return;

        string emailEnd = downloadEmail.Substring(downloadEmail.IndexOf('@') + 1);
        if (emailEnd == "")
            return;
        if (emailEnd == "worldbank.org")
        {
            SmtpClient smtpSender = new SmtpClient("smtp.gmail.com", 587);
            smtpSender.Credentials = new NetworkCredential("worldbank@thetigerparty.com", "gogotiger");
            smtpSender.EnableSsl = true;

            MailMessage msg = new MailMessage();
            msg.To.Add(downloadEmail);
            msg.From = new MailAddress("M-APP Photo Diary <wbmapp@gmail.com>");

            msg.Subject = "M-APP Photo Diary";
            string htmlBody = @"<br><br>You can download the latest version of the M-APP Photo Diary from the link below:<br><a href=\""http://devtest.wearepassionfruit.com/1.0.3/WorldBank.jad\"">http://devtest.wearepassionfruit.com/1.0.3/WorldBank.jad</a><br><br>Thank you and please let us know what you think.<br><br><img src=\""http://worldbank.thetigerparty.com/images/Mapp_Logo.png\"" style=\""display:block\"" />";
            msg.Body = htmlBody;
            msg.IsBodyHtml = true;

            try
            {
                smtpSender.Send(msg);
            }
            catch (Exception ex)
            {
                Console.WriteLine("GAN!:{0}", ex.ToString());
            }

            script = @"alert(""Download Link for the App has been sent to " + downloadEmail + "\")";
            ScriptManager.RegisterClientScriptBlock(DownloadPanel, typeof(UpdatePanel), "jscript", script, true);
        }
        else
        {
            script = @"alert(""Currently we are only accepting download request from @WorldBank.org"")";
            ScriptManager.RegisterClientScriptBlock(DownloadPanel, typeof(UpdatePanel), "jscript", script, true);
        };
    }
}